#!/bin/bash

# 全部服务启动脚本
# All Services Startup Script

set -e

echo "🚀 启动所有服务..."
echo "================================"

# 获取脚本目录
SCRIPT_DIR="$(dirname "$0")"

# 检查 Docker 和 Docker Compose
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装，请先安装 Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo "❌ Docker Compose 未安装，请先安装 Docker Compose"
    exit 1
fi

# 进入项目根目录
cd "$SCRIPT_DIR/.."

echo "📁 当前目录: $(pwd)"

# 使用新版本的 docker compose 或旧版本的 docker-compose
if docker compose version &> /dev/null; then
    COMPOSE_CMD="docker compose"
else
    COMPOSE_CMD="docker-compose"
fi

echo "🗄️  启动数据库服务..."
$COMPOSE_CMD up -d mysql redis

echo "⏳ 等待数据库启动..."
sleep 15

echo "🏗️  构建并启动后端服务..."
$COMPOSE_CMD up -d --build backend

echo "⏳ 等待后端服务启动..."
sleep 10

echo "🎨 构建并启动前端服务..."
$COMPOSE_CMD up -d --build frontend

echo "🌐 启动 Nginx 网关..."
$COMPOSE_CMD up -d nginx

echo "📊 启动监控服务..."
$COMPOSE_CMD up -d prometheus grafana

echo "⏳ 等待所有服务启动完成..."
sleep 20

# 检查所有服务状态
echo "📊 检查服务状态..."
$COMPOSE_CMD ps

echo ""
echo "✅ 所有服务启动完成！"
echo "================================"
echo "🌐 前端访问地址: http://localhost"
echo "🔧 后端 API: http://localhost/api"
echo "📚 Swagger 文档: http://localhost/api"
echo "📊 Grafana 监控: http://localhost:3000 (admin/admin123)"
echo "📈 Prometheus: http://localhost:9090"
echo "🗄️  MySQL: localhost:3306 (admin/admin123)"
echo "🔴 Redis: localhost:6379 (redis123)"
echo ""
echo "🛑 停止所有服务: $COMPOSE_CMD down"
echo "🗑️  清理所有数据: $COMPOSE_CMD down -v"